<?php
class Tamtay_Base_Action extends Zend_Controller_Action
{
    protected static $data_cache = null;
    protected static $data_cachedb = null;
    
    public function preDispatch()
    {
        $view = $this->_helper->viewRenderer->view;
        
        if ($view!=null)
        {
            $view->controller=$this;
        }
    }
    
    public function setTitle($title)
    {
        $layout = Zend_Layout::getMvcInstance();
        if ($layout)
        {
            $layout->title=$title;
        }
    }
    
    public function isLogin()
    {
        $user=$this->getUser();
        return ($user->uid>0);
    }
    
    public function getUser()
    {
        return Zend_Registry::get("user");
    }

    public function loadModel($model, $module)
    {
        return AppGlobal::loadModel($model, $module);        
    }
    
    //memcachedb version
    private static function getCacheDbEngine()
    {
        if (!MEMCACHEDB_ENABLED)
        {
            return null;
        }
        if (self::$data_cachedb==null)
        {
            $reg=Zend_Registry::getInstance();
            $frontendOptions=array(
                'cache_id_prefix' => 'tamtay_',
                'lifetime' => 1200,
                'automatic_serialization' => true
            );
            $backendOptions=$reg->memcachedb;
            self::$data_cachedb = Zend_Cache::factory('Core',    'Memcached', $frontendOptions, $backendOptions);
        }
        return self::$data_cachedb;
    }
    
    private function getCacheDb($key)
    {
        if (!MEMCACHEDB_ENABLED)
        {
            return false;
        }
        $cache_eng=self::getCacheDbEngine();
        $time = time();
        $ttl = 300;
        
        $cache=false;
        if (!$cache = $cache_eng->load($key))
        {
            $this->cacheStats($key, "cachedb_abs_miss");
            return false;
        }
        else
        {
            if (($time - $ttl) > ($cache->created + $cache->expire))
            {
                $cache->created = $time;            
                $cache_eng->save($cache, $key, array(), $ttl);
                $this->cacheStats($key, "cachedb_sem_miss");
                return false;
            }
            $this->cacheStats($key, "cachedb_hit");
            return $cache;
        }
    }
    
    private function setCacheDb($key, $data, $timeout=1200)
    {
        if (!MEMCACHEDB_ENABLED)
        {
            return false;
        }
        $cache_eng=self::getCacheDbEngine();
        $time             = time();
        $ttl             = 300;    
        $cache             = new stdClass;
        $cache->data     = is_object($data) ? clone($data) : $data;
        $cache->created = $time;
        $cache->expire     = $timeout;
        $cache_eng->save($cache, $key, array(), $timeout + $ttl);
        
        $this->cacheStats($key, "cachedb_set");
    }
    
    protected function deleteCacheDb($key)
    {
        if (!MEMCACHEDB_ENABLED)
        {
            return false;
        }
        $cache_eng=self::getCacheDbEngine();
        $cache_eng->remove($key);
    }
    //
    
    protected static function getCacheEngine()
    {
        if (self::$data_cache==null)
        {
            $reg=Zend_Registry::getInstance();
            $frontendOptions=array(
                'cache_id_prefix' => 'tamtay_',
                'lifetime' => 1200,
                'automatic_serialization' => true
            );
            $backendOptions=$reg->memcached;
            self::$data_cache = Zend_Cache::factory('Core',    'Memcached', $frontendOptions, $backendOptions);
        }
        return self::$data_cache;
    }
    
    public function getCache($key)
    {
        $key = str_replace('-', '_', $key);
        $cache_eng=self::getCacheEngine();
        $time = time();
        $ttl = 300;
        
        $cache=false;
        
        if (!$cache = $cache_eng->load($key))
        {
            $this->cacheStats($key, "cache_abs_miss");
            
            $cache=$this->getCacheDb($key);
            if ($cache!==false)
            {
                $expire=($cache->created + $cache->expire) - $time;
                if ($expire<=0)
                {
                    $expire=$ttl;
                }
                $this->setCache($key, $cache->data, $expire, false);
                return $cache->data;
            }
            return false;
        }
        else
        {
            if (($time - $ttl) > ($cache->created + $cache->expire))
            {
                $cache->created = $time;            
                $cache_eng->save($cache, $key, array(), $ttl);
                $this->cacheStats($key, "cache_sem_miss");
                return false;
            }
            $this->cacheStats($key, "cache_hit");
            return $cache->data;
        }
    }
    
    public function setCache($key, $data, $timeout=1200, $setdb=true)
    {
        $key = str_replace('-', '_', $key);
        $cache_eng=self::getCacheEngine();
        $time             = time();
        $ttl             = 300;    
        $cache             = new stdClass;
        $cache->data     = is_object($data) ? clone($data) : $data;
        $cache->created = $time;
        $cache->expire     = $timeout;
        $cache_eng->save($cache, $key, array(), $timeout + $ttl);
        if ($setdb)
        {
            $this->setCacheDb($key, $data, $timeout);
        }
        $this->cacheStats($key, "cache_set");
    }
    
    public function deleteCache($key)
    {
        $cache_eng=self::getCacheEngine();
        $cache_eng->remove($key);
        
        $this->deleteCacheDb($key);
    }
    
    private function cacheStats($key, $status)
    {
        if ($GLOBALS['_DBG'])
        {
            $stats=Zend_Registry::get("cache_stats");
            $stats[$status][]=$key;
            Zend_Registry::set("cache_stats", $stats);
        }
    }   
    
    //lazy load user roles
    public function loadUserRoles()
    {
        $u=Zend_Registry::get("user");
        if ($u->uid==0)
        {
            return;
        }
        if ($u->roles_loaded)
        {
            return;
        }
        
        $r_model=$this->loadModel("Role", "default");
        $roles=$r_model->getUserRoles($u->uid);
        for ($i=0; $i<count($roles); $i++)
        {
            $r=$roles[$i];
            $u->roles[$r->rid]=$r->name;
        }
        $u->roles_loaded=true;
        Zend_Registry::set("user", $u);
    }
    
    //Lazy load user permissions
    public function loadUserPermissions()
    {
        $u=Zend_Registry::get("user");
        if ($u->uid==0)
        {
            return;
        }
        if ($u->perms_loaded)
        {
            return;
        }
        
        if (!$u->roles_loaded)
        {
            $this->loadUserRoles();
        }
        
        $p_model=$this->loadModel("Perms", "default");
        $perms=$p_model->getUserPermissions($u->uid, array_keys($u->roles));
        for ($i=0; $i<count($perms); $i++)
        {
            $u->perms = $u->perms . $perms[$i]->perm . ", ";
        }
        $u->perms_loaded=true;
        Zend_Registry::set("user", $u);
    }
    
    //check current user permission
    public function hasPerm($perm)
    {
        $u=Zend_Registry::get("user");          
        if (!$u->perms_loaded)
        {
            $this->loadUserPermissions();
        }
        return strpos($u->perms, "$perm, ") !== FALSE;
    }
    
    public function addModLog($module, $uid, $action, $ref, $note) 
    {
        $modModel = AppGlobal::loadModel('ModLog', 'default');
       // $modModel->add($module, $uid, $action, $ref, $note);
    }
    
    public function renderView($view, $template, $data){
    	if (count($data)>0){
    		foreach($data as $key => $value){
    			$view->$key=$value;
    		}
    	}
    	$res=$view->render($template);
    	if (count($data)>0){
    		foreach($data as $key => $value){
    			unset($view->$key);
    		}
    	}
    	return $res;
    }
}

